﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lamex.mNC.Common
{
    public class GetTxtFile
    {
        /// <summary>
        /// 生成txt
        /// </summary>
        /// <param name="fs">数据流</param>
        /// <param name="out_put_txt">文件内容</param>
        public static void GetTxtNodes(FileStream fs, string out_put_txt)
        {
            StreamWriter sw = new StreamWriter(fs);
            //开始写入       
            sw.Write(out_put_txt);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }

        /// <summary>
        /// 修改文件内容的方法
        /// </summary>
        /// <param name="oldLineValue">修改的旧值</param>
        /// <param name="newLineValue">修改的新值</param>
        /// <param name="patch">文件路径</param>
        public static void EditTxtNodes(string oldLineValue, string newLineValue, string patch)
        {
            FileStream fs = new FileStream(patch, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8"));
            string nextLine;
            StringBuilder sb = new StringBuilder();
            while ((nextLine = sr.ReadLine()) != null)
            {
                string line = nextLine.ToString();
                if (line.Contains(oldLineValue))
                {
                    line = line.Replace(oldLineValue, newLineValue);
                }
                sb.Append(line + "\r\n");
            }
            sr.Close();
            fs.Close();
            FileStream fs1 = new FileStream(patch, FileMode.Open, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs1, Encoding.GetEncoding("utf-8"));
            sw.Write(sb.ToString());
            sw.Close();
            fs1.Close();
        }
    }
}
